package canss.webservice.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import canss.supports.basic;
import canss.webservice.service.PortalIntraWebServiceControl;
import canss.webservice.service.PortalIntraWebServiceControlBean;

public class svtAjaxGetKey extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet
{
	private static final long serialVersionUID = 3639275433104747879L;

	public svtAjaxGetKey()
	{
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}
	
	PortalIntraWebServiceControl control; // control = (control==null)?new
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html; charset=UTF-8");
		StringBuffer retstr = new StringBuffer();
		PrintWriter out = response.getWriter();

		String _key = null;
		String _method = request.getParameter("_method");
		
		control = (control == null) ? new PortalIntraWebServiceControlBean() : control;
		if( basic.isEmpty(_method) )
		{
			try
			{
				String _pid = request.getParameter("_pid");
				String _pw = request.getParameter("_pw");
				
				if (!basic.isEmpty(_pid) && !basic.isEmpty(_pw))
				{
					_key = control.getKeyByPersonID(_pid, _pw);
					if( basic.isEmpty(_key) )
						_key="";//_key = control.createPersonKey(_pid, _pw);//from now.
				}
			} catch (RuntimeException e)
			{
				e.printStackTrace();
				retstr.append(e.toString() + "<br/>");
			}
			out.write(retstr.toString());
		}else
		{
			String _pid = request.getParameter("_pid");
			if( !basic.isEmpty(_pid))
			{
				if( "add".equalsIgnoreCase(_method) )
				{
					String ret = control.createPersonKeyByAdmin(_pid);
					if(ret!=null && ret.length()>0)
						out.write("succeed:"+ret);
					else
						out.write("failed:createpersonkeybyadmin");
				}else if( "remove".equalsIgnoreCase(_method) )
				{
					Boolean ret = control.deletePersonKey(_pid);
					if(ret!=null && ret)
						out.write("succeed:"+ret);
					else
						out.write("failed:deletepersonkey");
				}
			}
		}
		String _rurl = request.getParameter("_rurl");
		if (!basic.isEmpty(_rurl))
		{
			if( basic.isEmpty(_method) )
			{
				if( !basic.isEmpty(_key) )
				{
					request.getSession().setAttribute("_key", _key);
					request.getSession().removeAttribute("_keyerror");
				}else
					request.getSession().setAttribute("_keyerror", "wrong password");
			}
			response.sendRedirect(response.encodeRedirectURL(_rurl));
		}
	}
}